<script setup lang="ts">
import { onMounted, ref, defineProps, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

interface ManagementModel {
  id: number
  bomId: string
  bomTheme: string
  productNumber: string
  productName: string
  specification: string
  productId: string
  unit: string
  brand: string
  defaultBOM: string
  dailyOutput: string
  itemIds: string | null
  processFlowIds: string | null
}

const props = defineProps<{ tabKey: string }>()
const loading = ref(false)
const detail = ref<ManagementModel | null>(null)

// Tabs
const activeTab = ref<'info' | 'items'>('info')

// BOM配件数据
interface ItemModel {
  id: number
  itemNumber?: string
  itemName?: string
  specificationModel?: string
  unit?: string
  itemCategory?: string
  itemClassification?: string
  brand?: string
  totalInventory?: number
}
const itemsLoading = ref(false)
const bomItems = ref<ItemModel[]>([])
let hasLoadedItems = false

// 从sessionStorage获取BOM数据
function getBOMFromStorage(id: string | number): ManagementModel | null {
  const tabKey = `bom-detail-${id}`
  try {
    const stored = sessionStorage.getItem(tabKey)
    if (stored) {
      return JSON.parse(stored) as ManagementModel
    }
  } catch (e) {
    console.error('Failed to parse stored BOM data:', e)
  }
  return null
}

async function fetchDetail(id: string | number) {
  loading.value = true
  try {
    // 首先尝试从sessionStorage获取数据
    const storedData = getBOMFromStorage(id)
    if (storedData) {
      detail.value = storedData
      loading.value = false
      return
    }

    // 如果sessionStorage中没有数据，则通过API查询
    const resp = await axios.post(
      'http://localhost:5233/api/Management/query',
      { pageIndex: 1, pageSize: 1, keyword: String(id) },
      { headers: { 'Content-Type': 'application/json' } }
    )
    const data = resp.data
    if (data?.code === 200 && Array.isArray(data.pageData)) {
      detail.value = data.pageData.find((x: any) => Number(x.id) === Number(id)) || data.pageData[0] || null
    } else {
      ElMessage.error(data?.msg || '查询详情失败')
    }
  } catch (e) {
    ElMessage.error('请求失败，请检查后端接口')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const idStr = props.tabKey?.replace('bom-detail-', '')
  if (idStr) fetchDetail(idStr)
})

// 解析 detail.itemIds -> number[]
function getItemIdList(): number[] {
  const idsStr = detail.value?.itemIds || ''
  return idsStr
    .split(',')
    .map(s => Number((s || '').trim()))
    .filter(n => !Number.isNaN(n) && n > 0)
}

// 根据 itemIds 查询BOM配件
async function fetchItemsByIds() {
  const idList = getItemIdList()
  if (idList.length === 0) {
    bomItems.value = []
    return
  }
  itemsLoading.value = true
  try {
    // 兼容不同后端参数命名，逐一尝试直到拿到数据
    const base = { pageIndex: 1, pageSize: 1000 }
    const candidates = [
      { ...base, ids: idList },
      { ...base, idList: idList },
      { ...base, itemIds: idList.join(',') },
      { ...base, ids: idList.join(',') },
      { ...base, idList: idList.join(',') }
    ]

    let fetched: any[] = []
    for (const payload of candidates) {
      try {
        const resp = await axios.post(
          'http://localhost:5227/api/Item/query',
          payload,
          { headers: { 'Content-Type': 'application/json' } }
        )
        const data = resp.data
        const pageData = Array.isArray(data?.pageData)
          ? data.pageData
          : Array.isArray(data?.data)
          ? data.data
          : Array.isArray(data)
          ? data
          : []
        if (Array.isArray(pageData) && pageData.length > 0) {
          fetched = pageData
          break
        }
      } catch {
        // 继续尝试下一个payload
      }
    }

    // 前端再按 id 严格过滤一遍
    const allow = new Set(idList.map(Number))
    const filtered = (fetched as any[]).filter(x => allow.has(Number(x.id)))
    bomItems.value = filtered as ItemModel[]

    // 若仍为空，降级逐个按ID查询
    if (bomItems.value.length === 0) {
      const results: any[] = []
      await Promise.all(
        idList.map(async (id) => {
          try {
            const r = await axios.get(`http://localhost:5227/api/Item/${id}`)
            const d = r.data
            const item = Array.isArray(d?.data) ? d.data[0] : d?.data || d
            if (item && item.id) results.push(item)
          } catch {
            // 忽略单个失败
          }
        })
      )
      bomItems.value = results.filter(x => allow.has(Number(x.id))) as ItemModel[]
    }

    if (bomItems.value.length === 0) {
      ElMessage.warning('未查询到与 ItemIds 对应的BOM配件')
    }
  } catch (e) {
    ElMessage.error('请求失败，请检查后端接口')
  } finally {
    itemsLoading.value = false
  }
}

// 首次切到BOM配件时加载
watch(activeTab, (tab) => {
  if (tab === 'items' && !hasLoadedItems) {
    hasLoadedItems = true
    fetchItemsByIds()
  }
})

// 详情变化时重置配件数据
watch(detail, () => {
  hasLoadedItems = false
  bomItems.value = []
  if (activeTab.value === 'items') {
    hasLoadedItems = true
    fetchItemsByIds()
  }
})
</script>

<template>
  <div style="padding: 16px 20px;">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="BOM信息" name="info">
        <el-card shadow="never">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span style="font-size: 18px; font-weight: bold;">BOM信息</span>
            </div>
          </template>

          <!-- 基础信息（自定义样式，无表格） -->
          <div v-loading="loading">
            <div class="section-title">
              <span class="dot" /> 基础信息
            </div>
            <div class="info-grid">
              <div class="info-row">
                <div class="info-item"><span class="label">BOM编号：</span><span class="value">{{ detail?.bomId || '-' }}</span></div>
                <div class="info-item"><span class="label">BOM主题：</span><span class="value">{{ detail?.bomTheme || '-' }}</span></div>
              </div>
              <div class="info-row">
                <div class="info-item"><span class="label">默认BOM：</span><span class="value">{{ detail?.defaultBOM || '-' }}</span></div>
                <div class="info-item"><span class="label">版本：</span><span class="value">{{ '1.1' }}</span></div>
              </div>
              <div class="info-row">
                <div class="info-item"><span class="label">成品编号：</span><span class="value">{{ detail?.productNumber || '-' }}</span></div>
                <div class="info-item"><span class="label">成品名称：</span><span class="value">{{ detail?.productName || '-' }}</span></div>
              </div>
              <div class="info-row">
                <div class="info-item"><span class="label">日产量：</span><span class="value">{{ detail?.dailyOutput || '-' }}</span></div>
                <div class="info-item"><span class="label">产品ID：</span><span class="value">{{ detail?.productId || '-' }}</span></div>
              </div>
              <div class="info-row">
                <div class="info-item"><span class="label">预计成本：</span><span class="value">{{ '8,000' }}</span></div>
                <div class="info-item"><span class="label">规格型号：</span><span class="value">{{ detail?.specification || '-' }}</span></div>
              </div>
              <div class="info-row">
                <div class="info-item"><span class="label">单位：</span><span class="value">{{ detail?.unit || '-' }}</span></div>
                <div class="info-item"><span class="label">品牌：</span><span class="value">{{ detail?.brand || '-' }}</span></div>
              </div>
              <div class="info-row">
                <div class="info-item" style="width: 100%;"><span class="label">备注：</span><span class="value">-</span></div>
              </div>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="BOM配件" name="items">
        <el-card shadow="never">
          <template #header>
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <span style="font-size: 18px; font-weight: bold;">BOM配件</span>
            </div>
          </template>
          <el-table :data="bomItems" v-loading="itemsLoading" border>
            <el-table-column type="index" label="序号" width="70" align="center" />
            <el-table-column prop="itemNumber" label="物品编号" min-width="140" />
            <el-table-column prop="itemName" label="物品名称" min-width="160" />
            <el-table-column prop="specificationModel" label="规格型号" min-width="160" />
            <el-table-column prop="unit" label="单位" width="100" />
            <el-table-column prop="itemCategory" label="物品类别" min-width="120" />
            <el-table-column prop="itemClassification" label="物品分类" min-width="120" />
            <el-table-column prop="brand" label="品牌" min-width="120" />
            <el-table-column prop="totalInventory" label="库存" width="100" />
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped>
/* 区块标题 */
.section-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
  display: flex;
  align-items: center;
}
.section-title .dot {
  width: 8px;
  height: 8px;
  background: #666;
  border-radius: 50%;
  display: inline-block;
  margin-right: 8px;
}

/* 信息栅格 */
.info-grid {
  padding: 8px 4px 0 4px;
}
.info-row {
  display: flex;
  gap: 24px;
  margin-bottom: 18px;
}
.info-item {
  flex: 1;
  color: #333;
  line-height: 24px;
}
.label {
  color: #666;
  margin-right: 8px;
}
.value {
  color: #111;
}
</style>


